07 / 16

How do you detect a cycle in a Linked List? (Floyd's Tortoise and Hare)

Floyd's Cycle Detection

javascript
  1. 1

    Time complexity: O(n).

  2. 2

    Auxiliary space: O(1).

  3. 3

    The algorithm does not require a HashSet of visited nodes.

  4. 4

    The meeting point confirms a cycle but is not necessarily the cycle's entry point.

  5. 5

    The same technique can be extended to locate the cycle entry.

Difficulty: 3/10
Topics: cycle detection, two-pointer technique, linked list

Scenario Questions

0-2 years experience
  1. 1

    Given a singly linked list implementation, how would you check if it contains a cycle using only O(1) extra space?

  2. 2

    If you run the two‑pointer algorithm on a list that has a self‑loop at the head, what will happen and why?

  3. 3

    What would you return when you detect a cycle, and how could you extend the function to also return the start node of the cycle?

2-5 years experience
  1. 1

    We have a production service that processes a stream of events stored in a linked list; recently we saw occasional infinite loops. Walk me through how you'd debug and confirm a cycle using Floyd's algorithm.

  2. 2

    Suppose you need to detect cycles but also count the number of nodes in the loop. How would you extend the tortoise‑hare approach?

  3. 3

    If the list can be modified, would you consider breaking the cycle after detection? What trade‑offs are involved?

5-8 years experience
  1. 1

    Our distributed cache uses a custom linked structure for LRU eviction across shards. How would you ensure cycle detection scales and doesn't become a bottleneck?

  2. 2

    When integrating a third‑party library that provides its own linked list, you notice memory leaks due to hidden cycles. How would you design a wrapper that safely detects and handles cycles?

  3. 3

    Discuss the performance implications of using Floyd's algorithm versus a hash‑set for cycle detection in a high‑throughput system, and when you might choose one over the other.

8+ years experience
  1. 1

    We are refactoring a legacy codebase where many modules use hand‑rolled linked lists that may contain cycles. How would you architect a migration strategy that introduces a unified cycle‑detection utility while minimizing risk across teams?

  2. 2

    Consider a microservices architecture where messages form a logical linked list across services, and cycles can cause deadlocks. How would you design a system‑wide contract or monitoring approach to detect and prevent cycles?

  3. 3

    What guidelines would you set for future data‑structure design to avoid hidden cycles, and how would you enforce them across multiple engineering teams?

Follow-up Questions

  • What is the time and space complexity of this approach?
  • How would you modify the algorithm to return the node where the cycle begins?
  • If the list were extremely large and stored on disk, would this technique still be appropriate?